/**
 * 
 *//*
package com.qhgrain.app.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.paas.bpm.util.http.client.RestCallDelegator;
import com.paas.bpm.util.http.client.WsRequest.Method;
import com.paas.common.util.CustomizedPropertyConfigurer;
import com.paas.model.sys.Organization;
import com.paas.model.sys.Role;
import com.paas.model.sys.User;
import com.qhgrain.gway.util.ConfigUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

*//**
 * @author Administrator 系统自己定制的resttemplate用来访问微服务的类
 *//*
@Service("synchronizeDataService")
public class SynchronizeDataService {

	private static final Logger logger = LoggerFactory.getLogger(SynchronizeDataService.class);

	@Autowired
	private RestTemplate restTemplate;

	public static String HOST;
	public static String SSO_ORG;
	public static String SSO_USER;
	public static String SSO_GROUPS;
	public static String SSO_ORG_ROOT = "/青海粮食系统";
	public static String SSO_ORG_ROOT_ID;
	static {
		logger.debug("load HOST、SSO_ORG、SSO_SUB_ORG、SSO_USER values");
		// 获取微服务的url地址
		HOST = ConfigUtil.getAPIUrl("sso_host_url");
		// 获取查询所有部门的微服务接口
		SSO_ORG = ConfigUtil.getAPIUrl("sso.url.allOrg");
		// 获取根据部门ID查询部门下的员工的微服务接口
		SSO_USER = ConfigUtil.getAPIUrl("sso.url.userByOrg");
		//查询所有群组接口
		SSO_GROUPS = ConfigUtil.getAPIUrl("sso.url.queryAllGroups");
		
		SSO_ORG_ROOT_ID = ConfigUtil.getAPIUrl("sso.org.rootId");
	}

	*//********************************************** 通过rest服务获取数据  ****************************************//*
	//首先获取所有部门信息，由于所有的部门只有一个根节点，所以只要找到path=/的节点，其余的节点都为子节点
	public List<Organization> getOrgs(){
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("path", "/");
		//根据IAM提供的rest服务接口查询出第一级部门的信息
		JSONArray orgArray = this.askRestService(SSO_ORG,params);
		List<Organization> organizations = new ArrayList<Organization>();
		Map<String, String> orgNameIdMap = new HashMap<String,String>();
		orgNameIdMap.put(SSO_ORG_ROOT, SSO_ORG_ROOT_ID);
		//第一遍循环将根节点找到，然后将orgName对应的id找到，为了第二遍循环拼接orgIdPath
		if (orgArray != null && orgArray.size() > 0) {
			for (int i = 0 ,size = orgArray.size(); i < size; i++) {
				JSONObject jsonObject = orgArray.getJSONObject(i);
				//获取父节点的id
				String uuid = jsonObject.getString("uuid");
				String orgName = jsonObject.getString("displayName");
				String path = jsonObject.getString("path");
				//如果当前数据只有一个/杠则需要将orgname拼接到后面,否则就将根部门的名称拼接到所有path之前
				if (path.equals("/")) {
					path = SSO_ORG_ROOT + path + orgName;
					jsonObject.remove("path");
					jsonObject.accumulate("path", path);
					//将当前组织对应的id放到map中
					orgNameIdMap.put(path, uuid);
				}else{
					path = SSO_ORG_ROOT + path;
					jsonObject.remove("path");
					jsonObject.accumulate("path", path);
					//将当前组织对应的id放到map中
					orgNameIdMap.put(path, uuid);
				}
				
				//将jsonobject中多余的数据移除
				jsonObject.remove("attributes");
				jsonObject.remove("ldap");
			}
			String parentId = "0";
			for (int i = 0 ,size = orgArray.size(); i < size; i++) {
				JSONObject jsonObject = orgArray.getJSONObject(i);
				//获取父节点的id
				String id = jsonObject.getString("id");
				String uuid = jsonObject.getString("uuid");
				String orgName = jsonObject.getString("displayName");
				String path = jsonObject.getString("path");
				//将path通过/进行分割
				String[] orgNamePaths = path.split("/");
				StringBuilder sBuilder = new StringBuilder();
				
				if (orgNamePaths != null && orgNamePaths.length > 0) {
					//如果数组的长度为2，则表示当前节点为根节点
					if (orgNamePaths.length == 2) {
						parentId = "0";
					}else{
						String parentKey = orgNamePaths[orgNamePaths.length -1];
						//获取倒数第二级节点，然后获取其id
						int index = path.indexOf("/"+parentKey);
						if (index > 0) {
							//截取path的值
							String npath = path.substring(0,index);
							parentId = orgNameIdMap.get(npath);
						}
					}
					
					StringBuilder sPath = new StringBuilder();
					//由于数组的第一位为""所以要从第二个值开始取
					for(int j = 1 ;j < orgNamePaths.length;j++){
						sPath.append("/");
						String key = orgNamePaths[j];
						//根据循环的key来拼接路径，根据路径获取对应的id
						sPath.append(key);
						sBuilder.append(orgNameIdMap.get(sPath.toString()));
						sBuilder.append(".");
					}
				}
				
				Organization organization = new Organization();
				//将从json中获取的数据，设置到部门实体类中
				organization.setOrgId(uuid);
				organization.setParentOrgId(parentId);
				organization.setOrgCode(id);
				organization.setOrgName(orgName);
				organization.setSort(1);
				organization.setOrgType(2);
				organization.setOrgPath(sBuilder.toString());
				organization.setOrgPathName(path);
				organization.setCreateId("1");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date createDate = null;
				try {
					createDate = sdf.parse(getCurrentDate());
				} catch (ParseException e) {
					logger.debug("将create的string转换为date类型");
					e.printStackTrace();
				}
				organization.setCreateDate(createDate);
				
				organizations.add(organization);
				jsonObject.clear();
			}
			
			orgArray.clear();
			orgArray = null;
			orgNameIdMap.clear();
			orgNameIdMap = null;
		}
		return organizations;
	}
	
	*//**
	 * 获取所有的角色
	 * 
	 * @return
	 *//*
	public List<Role> getRoles() {
		//根据IAM提供的rest服务接口查询出第一级部门的信息
		JSONArray roleArray = this.askRestService(SSO_GROUPS,null);
		
		// 如果角色为null,则直接返回null
		if (roleArray == null || roleArray.size() == 0) {
			return null;
		}
		// 保存所有查询的角色信息的列表
		List<Role> roles = new ArrayList<Role>();
		if (roleArray != null && roleArray.size() > 0) {
			// 遍历所有用户
			for (int j = 0; j < roleArray.size(); j++) {
				// 获取
				JSONObject jObject = roleArray.getJSONObject(j);
				String id = jObject.getString("id");
				String uuid = jObject.getString("uuid");
				Role role = new Role();
				// role实体中必须录入的字段
				role.setRoleId(uuid);
				role.setRoleName(jObject.getString("name"));
				role.setRoleCode(id);
				role.setRoleDesc(jObject.getString("description"));
				role.setCreateId("1");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date createDate = null;
				try {
					createDate = sdf.parse(getCurrentDate());
				} catch (ParseException e) {
					logger.debug("将create的string转换为date类型");
					e.printStackTrace();
				}
				role.setCreateDate(createDate);
				role.setStatus(0);

				roles.add(role);
			}
		}
		roleArray.clear();
		roleArray = null;

		return roles;
	}
	
	public List<User> getUsers(){
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("path", "/");
		JSONArray orgArray = this.askRestService(SSO_ORG,params);
		return getAllUsers(orgArray);
	}
	
	public JSONArray getOrgs(){
		//根据IAM提供的rest服务接口查询出第一级部门的信息
		JSONArray orgArray = this.askRestService(SSO_ORG);
		JSONArray totalJsonArray = new JSONArray();
		//如果查询出来的第一级部门不为空，则获取其
		if (orgArray != null && orgArray.size() > 0) {
			for (int i = 0 ,size = orgArray.size(); i < size; i++) {
				JSONObject jsonObject = orgArray.getJSONObject(i);
				//获取父节点的id
				String id = jsonObject.getString("id");
				String orgName = jsonObject.getString("displayName");
				String path = jsonObject.getString("path");
				//如果当前数据只有一个/杠则需要将orgname拼接到后面
				if (path.equals("/")) {
					path = "/"+orgName;
				}
				JSONArray jsonArray = new JSONArray();
				//然后查询
				JSONArray array = getAllSubOrgs(id,id,jsonArray);
				//如果子部门为空，则直接跳过
				if (array == null || array.size() == 0) {
					continue;
				}
				for (int j = 0; j < jsonArray.size(); j++) {
					JSONObject jObject = jsonArray.getJSONObject(j);
					//将根节点拼接上
					String orgPath = path + jObject.getString(FieldConstant.ORG_PATH_NAME);
					jObject.remove(FieldConstant.ORG_PATH_NAME);
					//然后重新放入到json对象中
					jObject.accumulate(FieldConstant.ORG_PATH_NAME, orgPath);
					
					totalJsonArray.add(jObject);
				}
				//清空数组
				jsonArray.clear();
				jsonArray = null;
				
				//将当前jsonobject的保存到jsonarray中
				JSONObject json = new JSONObject();
				json.accumulate(FieldConstant.ORG_ID, id);
				json.accumulate(FieldConstant.PARENT_ORG_ID, 0);
				json.accumulate(FieldConstant.ORG_CODE, id);
				json.accumulate(FieldConstant.SORT, 1);
				json.accumulate(FieldConstant.ORG_TYPE, 2);
				json.accumulate(FieldConstant.ORG_PATH, id+".");
				json.accumulate(FieldConstant.ORG_NAME, orgName);
				json.accumulate(FieldConstant.ORG_PATH_NAME, jsonObject.getString("path"));
				//将组装好的json放到jsonarray中
				totalJsonArray.add(json);
			}
		}
		return totalJsonArray;
	}
	
	//通过深度遍历遍历所有的部门信息
	protected JSONArray getAllSubOrgs (String parentOrgId,String orgParentPath,JSONArray totalJsonArray) {
		Assert.notNull(parentOrgId, "父节点的id不能为空");
		//将配置文件中查询子部门的连接中的%s替换为父级部门的id
		String url = SSO_SUB_ORG.replace("%s", parentOrgId);
		JSONArray subArray = this.askRestService(url);
		//如果查询出来的数据不为空则进行递归调用
		if (subArray != null && subArray.size() > 0) {
			for (int i = 0 ,size = subArray.size(); i < size; i++) {
				JSONObject jsonObject = subArray.getJSONObject(i);
				//获取父节点的id
				String id = jsonObject.getString("id");
				StringBuilder orgPath = new StringBuilder();
				orgPath.append(orgParentPath);
				orgPath.append(".");
				orgPath.append(id);
				//orgPath.append(".");
				//将当前jsonobject的保存到jsonarray中
				JSONObject json = new JSONObject();
				json.accumulate(FieldConstant.ORG_ID, id);
				json.accumulate(FieldConstant.PARENT_ORG_ID, parentOrgId);
				json.accumulate(FieldConstant.ORG_CODE, id);
				json.accumulate(FieldConstant.SORT, 1);
				json.accumulate(FieldConstant.ORG_TYPE, 4);
				json.accumulate(FieldConstant.ORG_PATH, orgPath.toString()+".");
				json.accumulate(FieldConstant.ORG_NAME, jsonObject.getString("displayName"));
				json.accumulate(FieldConstant.ORG_PATH_NAME, jsonObject.getString("path"));
				//将组装好的json放到jsonarray中
				totalJsonArray.add(json);
				//循环递归其子节点
				JSONArray array = getAllSubOrgs(id,orgPath.toString(),totalJsonArray);
				//如果子部门为空，则直接跳过
				if (array == null || array.size() == 0) {
					continue;
				}
			}
		}
		return subArray;
	}
	
	//根据所有的部门ID获取，部门下面的所有用户
	protected List<User> getAllUsers (JSONArray jsonArray) {
		//如果部门为null,则直接返回null
		if (jsonArray == null || jsonArray.size() == 0) {
			return null;
		}
		String userUrl = SSO_USER;
		//保存所有查询的用户信息的列表
		List<User> users = new ArrayList<User>();
		//循环遍历查询出来的部门信息列表，然后获取所有部门的id，根据部门的id查询部门下的用户信息
		for (int i = 0, size = jsonArray.size(); i < size; i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String orgId = jsonObject.getString("uuid");
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("type", 2);
			//将链接中的%s替换为部门的id
			String url = userUrl.replace("%s", orgId);
			//根据url查询出来用户
			JSONArray jArray = askRestService(url,params);
			if (jArray != null && jArray.size() > 0) {
				//遍历该部门下的所有用户
				for (int j = 0; j < jArray.size(); j++) {
					//获取
					JSONObject jObject = jArray.getJSONObject(j);
					String id = jObject.getString("id");
					JSONObject attrObject = jObject.getJSONObject("attributes");
					
					User user = new User();
					//user实体中必须录入的字段
					user.setUserId(attrObject.getString("guid"));
					user.setOrgId(orgId);
					user.setEmployeeId(id);
					user.setUserName(attrObject.getString("sn"));
					user.setAccount(attrObject.getString("cn"));
					user.setPassword(attrObject.getString("userpwdbackup"));
					user.setEmployeeName(attrObject.getString("sn"));
					user.setEmployeeNo(id);
					user.setCompanyId(orgId);
					user.setCreateId("1");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					Date createDate = null;
					try {
						createDate = sdf.parse(getCurrentDate());
					} catch (ParseException e) {
						logger.debug("将create的string转换为date类型");
						e.printStackTrace();
					}
					user.setCreateDate(createDate);
					user.setStatus(0);
					
					users.add(user);
					jObject.remove("attributes");
				}
			}
		}
		return users;
	}
	
	*//**
	 * 具体使用httpclient访问rest服务的方法
	 * 
	 * @return
	 *//*
	protected JSONArray askRestService(String resUrl,Map<String, Object> map) {
		// 拼接微服务服务器地址和查询所有部门的接口连接
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append(HOST);
		sBuilder.append(resUrl);
		//String url = "http://172.16.16.25:8180/iam/v1/depts/queryDeptsByParentPath/2";
		logger.debug("use restTemplate to get the org values");
		// 执行获取部门数据的方法
		String result = this.excutePost(sBuilder.toString(),map);
		JSONObject jObject = JSONObject.fromObject(result);
		String data = jObject.getString("data");
		if (StringUtils.isBlank(data)) {
			logger.warn("askRestService调用，未查询到相关用户数据！参数：resUrl={}", resUrl);
			return null;
		}
		//判断接口返回字符串
		char c = data.charAt(0);
		if (c == '{') {
			data = "["+data+"]";
		}
		return JSONArray.fromObject(data);
	}

	// 执行GET方法
	@SuppressWarnings("hiding")
	protected <T> T excuteGet(String url, Class<T> clazz) {
		T result = restTemplate.getForObject(url, clazz);
		return result;
	}
	
	// 执行POST方法
	protected String excutePost(String url, Map<String,Object> map) {
		String result = RestCallDelegator.httpCall(url, map, Method.POST);
		return result;
	}
	
	public String getCurrentDate() {
		String formatter = "yyyy-MM-dd hh:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(formatter);
		String date = sdf.format(new Date());
		return date;
	}
	
}
*/